/*--------------------------------------------------------------------------------
 * 
 *
 * ===Copyright===
 * Copyright (C) 2008 toge (toge.mail@gmail.com)
 * (See Copyright Notice at COPYRIGHT file)
 *
 * ===Licence===
 * Mit License
 *
 * ===Revision===
 * $Revision: 117 $
 -------------------------------------------------------------------------------*/
#include <cmath>
#include <boost/tuple/tuple.hpp>

#include "TexGen.h"

inline
float
adjustX(float x)
{
  if (x > 0.5f)
  {
    return (1.0f - x) * 2;
  }
  return x * 2;
}

namespace PlayerTail
{

static
boost::tuple<Uint8, Uint8, Uint8>
genColor(float x, float y)
{
  float alpha = adjustX(x);

  const float ALPHA = 0.6f;
  if (alpha >= ALPHA)
  {
    alpha = 1.0f;
  }
  else
  {
    alpha = std::sqrt(alpha / ALPHA);
  }

  Uint8 color[] =
    {
      0xFF, 0xFF, 0xFF,
      0x00, 0x00, 0xFF
    };

  Uint8 r = (Uint8)((color[0] - color[3]) * alpha + color[3]);
  Uint8 g = (Uint8)((color[1] - color[4]) * alpha + color[4]);
  Uint8 b = (Uint8)((color[2] - color[5]) * alpha + color[5]);

  return boost::make_tuple(r, g, b);
}

static
Uint8
genAlpha(float x, float y)
{
  float alpha = adjustX(x);
  
  const float ALPHA = 0.3f;
  if (alpha >= ALPHA)
  {
    alpha = 1.0f;
  }
  else
  {
    alpha = std::sqrt(alpha / ALPHA);
  }

  int val = (int)(alpha * 256);
  if (val >= 256)
  {
    val = 255;
  }

  return val;
}

};

SDL_Surface*
TexGenPlayerTail::generate(int width, int height)
{
  using namespace PlayerTail;

  SDL_Surface* surface = NULL;

  surface = SDL_CreateRGBSurface(SDL_SWSURFACE,
                                 width, height, 32,
                                 0x000000FF,
                                 0x0000FF00,
                                 0x00FF0000,
                                 0xFF000000);

  SDL_LockSurface(surface);

  Uint8* pixels = (Uint8*)surface->pixels;
  int pitch = surface->pitch;

  for (int y = 0; y < height; ++y)
  {
    float alphaY = (float)y / height;

    for (int x = 0; x < width; ++x)
    {
      float alphaX = (float)x / width;

      Uint8 r, g, b, a;

      boost::tie(r, g, b) = genColor(alphaX, alphaY);
      a = genAlpha(alphaX, alphaY);

      pixels[x * 4 + 0] = r;
      pixels[x * 4 + 1] = g;
      pixels[x * 4 + 2] = b;
      pixels[x * 4 + 3] = a;
    }

    pixels += pitch;
  }

  SDL_UnlockSurface(surface);

  return surface;
}
